package modules

import (
	"fmt"
	"service/components"

	"gorm.io/gorm"
)

type Menu struct {
	gorm.Model
	Name     string `json:"name" gorm:"type:varchar(300);comment:菜单的名字"`
	Icon     string `json:"icon" gorm:"type:varchar(300);comment:图标"`
	Path     string `json:"path" gorm:"type:varchar(300);comment:路径"`
	IsParent uint   `json:"is_parent" gorm:"type:int(5);comment:父级"`
	File     string `json:"file" gorm:"type:varchar(300);comment:文件位置"`
	UUID     *uint  `json:"uuid"`
	Children []Menu `json:"children" gorm:"foreignKey:UUID"`
}

func (receiver Menu) TableName() string {
	return "menu"
}

// PostMenuService 增加菜单
func PostMenuService(m *Menu) error {
	return components.DB.Model(&Menu{}).Create(m).Error
}

// FetchMenuService 获取菜单
func FetchMenuService(ids string) ([]*Menu, error) {
	m := make([]*Menu, 20)
	var err error
	str := fmt.Sprintf("id in (%s)", ids)
	if ids != "" {
		err = components.DB.Model(&Menu{}).Where(str).Find(&m).Error
	} else {
		err = components.DB.Model(&Menu{}).Find(&m).Error
	}
	return m, err
}

// PatchMenuService 更新菜单
func PatchMenuService(m *Menu) error {
	return components.DB.Model(&Menu{}).Where("id = ?", m.ID).Updates(map[string]interface{}{
		"is_parent": m.IsParent,
		"name":      m.Name,
		"icon":      m.Icon,
		"path":      m.Path,
		"file":      m.File,
	}).Error
}
